//
//  OAuthViewController.m
//  王雷Sinoweibo
//
//  Created by wanglei on 16/10/30.
//  Copyright © 2016年 wanglei. All rights reserved.
//

#import "OAuthViewController.h"
#import "SVProgressHUD/SVProgressHUD.h"
#import "AFNetworking.h"
@interface OAuthViewController()<UIWebViewDelegate>

@end

@implementation OAuthViewController

-(void)loadView{
    UIWebView *Webview = [[UIWebView alloc]init];
    _webview = Webview;
    self.view = _webview;
    _webview.delegate = self;
    [self loadOauthPage];
    
}

- (void)close{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



- (void)AccountFortest{
    
    NSString *str = @"document.getElementById('userId').value = '1039448826@qq.com',document.getElementById('passwd').value = 'wang814'";
    
    [self.webview stringByEvaluatingJavaScriptFromString:str];
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"测试" style:UIBarButtonItemStylePlain target:self action:@selector(AccountFortest)];
    
}

- (void)loadOauthPage{
    //    NSString *urlstring = @"https://api.weibo.com/oauth2/authorize?client_id=1035928713&redirect_uri=https://www.baidu.com";
    
    NSString *urlstring = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",client_id,redirect_uri];
    
    NSURL *url = [NSURL URLWithString:urlstring];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [self.webview loadRequest:request];
    
}


//webview的代理方法的实现
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;{
    
    //    NSLog(@"%@",request.URL);
    NSString *urlstr = [request.URL absoluteString];
    
    if (urlstr != nil) {
        
        if ([urlstr containsString:@"code"]) {
            
            
            if (request.URL.query != nil) {
                
                //   https://m.baidu.com/?code=788337cbdf165c21f12eb37b8cdb4b97&from=844b&vit=fps
                
                
                NSLog(@"%@",request.URL.query);
                //  code=761de8280047af4ceb024f975a1decbf&from=844b&vit=fps
                
                NSRange range = NSMakeRange(5, 32);
                
                NSString *code = [request.URL.query substringWithRange:range];
                
                NSLog(@"%@",code);
                
                [self loadAccessToken:code];
                
                return false;
                
            }
            return false;
            
        }
        
        return true;
        
        
    }
    return false;
    
}





- (void)loadAccessToken:(NSString *)code{
    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
    NSDictionary *parameters = @{@"client_id":client_id,@"client_secret": client_secret,@"grant_type":@"authorization_code",@"code":code,@"redirect_uri":redirect_uri};
    AFHTTPSessionManager *AFN = [AFHTTPSessionManager manager];
        //    AFN.responseSerializer.acceptableContentTypes 不支持@"text/plain",此时要头文件"AFURLResponseSerialization.m"的如下地方添加text/plain就行了,即  self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain",@"text/json", @"text/javascript", nil];
    
    [AFN POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        NSLog(@"%@",responseObject);
        
        NSString *access_token = responseObject[@"access_token"];
        NSString *uid = responseObject[@"uid"];
        NSLog(@"------%@-----",access_token);
        NSLog(@"------%@-----",uid);
        
        [self loadUserInfoAccess_token:access_token uid:uid];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}

- (void)loadUserInfoAccess_token:(NSString *)access_token uid:(NSString *)uid{
    
    
    
    AFHTTPSessionManager *AFN = [[AFHTTPSessionManager alloc]init];
    
    NSString *urlStr = @"https://api.weibo.com/2/users/show.json";
    NSDictionary *parameter = @{@"access_token":access_token,@"uid":uid};
    
    [AFN GET:urlStr parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        
        NSLog(@"%@",responseObject);
        
        NSString *name = responseObject[@"name"];
        NSString *avatar_large = responseObject[@"avatar_large"];
        
        NSLog(@"%@,%@",name,avatar_large);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}



- (void)webViewDidStartLoad:(UIWebView *)webView;{
    
    [SVProgressHUD show];
    
}



- (void)webViewDidFinishLoad:(UIWebView *)webView;{
    
    [SVProgressHUD dismiss];
}


@end
